package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.sky.properties.AliOssProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;


@Slf4j
@Component
public class AliOssUtil {
    private final OSS ossClient;
    private final AliOssProperties aliOssProperties;

    //使用构造器的方法注入
    public AliOssUtil(OSS ossClient,AliOssProperties aliOssProperties) {
        this.ossClient = ossClient;
        this.aliOssProperties = aliOssProperties;
    }
    //上传文件
    public String upload(byte[] bytes, String objectName) {
        try {
            // 上传文件到 OSS
            ossClient.putObject(aliOssProperties.getBucketName(), objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            log.error("OSSException: {}", oe.getErrorMessage(), oe);
            return null;
        } catch (ClientException ce) {
            log.error("ClientException: {}", ce.getMessage(), ce);
            return null;
        }
        // 文件访问路径规则: https://BucketName.Endpoint/ObjectName
        String fileUrl = String.format("https://%s.%s/%s", aliOssProperties.getBucketName(),aliOssProperties.getEndpoint(), objectName);
        log.info("文件上传成功: {}", fileUrl);
        return fileUrl;
    }
}
